import React from 'react'
import { BrowserRouter, useRoutes, useNavigate, useLocation, useSearchParams} from 'react-router-dom'
import routes from '~react-pages'
import './App.css'

const App = () => {

  //路由列表
  const Routes = () => 
  {
    //设置全局跳转路由函数
    React.navigate = useNavigate()

    //location.pathname
    const {pathname} = useLocation()
    
    //不在RouterRules数组中需要登录
    if(!React.RouterRules.includes(pathname)) check()

    //设置全局自动获取链接参数
    let [SearchParams] = useSearchParams()

    React.params = (name:string) => SearchParams.get(name ?? '')

    //返回自动生成的路由列表
    return useRoutes(routes)
  }

  //判断界面是否需要登录(路由守卫)
  const check = async () => 
  {
    let id = React.business.id ?? 0
    let mobile = React.business.mobile ?? ''

    //发送请求
    var result = await React.request.post('/business/check', {id, mobile})

    if(result.code == 0)
    {
      React.business = {}
      React.cookies.remove('business')

      React.toast('尚未登录', result.url, 'fail')
      return false
    }

    React.business = result.data
    React.cookies.save('business', result.data, {path: '/'})
  }

  return(
    <BrowserRouter future={{v7_startTransition: true, v7_relativeSplatPath: true}}>
      <Routes />
    </BrowserRouter>
  )

}

export default App
